package cn.gx.kevin.config;

import cn.gx.kevin.common.ui.AjaxResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class GlobalExceptionHandler extends AbstractErrorController {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    private final ErrorProperties errorProperties;

    @Autowired
    public GlobalExceptionHandler(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
        super(errorAttributes);
        this.errorProperties = serverProperties.getError();
        this.errorProperties.setIncludeException(true);
        this.errorProperties.setIncludeStacktrace(ErrorProperties.IncludeStacktrace.ALWAYS);
    }

    @Override
    public String getErrorPath() {
        return errorProperties.getPath();
    }

    @RequestMapping(produces = "text/html")
    public ModelAndView errorHtml(HttpServletRequest request,
                                  HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView("error");
        Map<String, Object> errorMap = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
        if (errorMap != null) {
            /*timestamp status error message path*/
            modelAndView.addObject("msg", errorMap.get("error"));
            modelAndView.addObject("statusCode", errorMap.get("status"));
            logHandler(errorMap);
        }
        return modelAndView;
    }

    @RequestMapping
    @ResponseBody
    public AjaxResult error(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> errorMap = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.APPLICATION_JSON));
        logHandler(errorMap);
        String msg = "SERVER EXCEPTIONS";
        Object msgObj = errorMap.get("message");
        if(msgObj != null){
            String tmp = String.valueOf(msgObj);
            if(StringUtils.isNotEmpty(tmp) && tmp.length() < 100){
                msg = tmp;
            }
        }
        AjaxResult result = new AjaxResult(500, msg);
        result.data = errorMap;
        response.setStatus(200);
        return result;
    }

    private void logHandler(Map<String, Object> errorMap) {
        String path = String.valueOf( errorMap.get("path"));
        logger.error("url:{},status{},time:{},errorMsg:{}", path, errorMap.get("status"), errorMap.get("timestamp"), errorMap.get("message"));
      }

    protected boolean isIncludeStackTrace(HttpServletRequest request,
                                          MediaType produces) {
        ErrorProperties.IncludeStacktrace include = getErrorProperties().getIncludeStacktrace();
        if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
            return true;
        }
        if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM) {
            return getTraceParameter(request);
        }
        return false;
    }

    private ErrorProperties getErrorProperties() {
        return this.errorProperties;
    }
}
